import SessionUtil, {
  JxbHttpClient
} from '../../../data/session/session'
import PagePromoterUtil, {
  PagePromoter
} from '../../../data/common/pagePromoter';
import AppSceneUtil from '../../../data/common/appScene';
import SystemUtil from '../../../shell/system/system';
const Common = require('../../../utils/common.js');
let pageSize = getApp().data.pageSize1;
import create from '../../../utils/create2.js'
import store from '../../../store/index.js'
import InteractionUtil from '../../../shell/ui/interaction';
import SessionSellingServerUtil from '../../../data/session/sessionSellingServer';
create(store, {
  data: {
    token: '',
    ItemList: {},
    by_volume: '',
    by_volumes: '../../images/sp_05.png',
    by_price: '',
    by_prices: '../../images/sp_05.png',
    productsList: {},
    chosenNum: 1,
    pageNo: 1,
    name: '',
    Type: '',
    categoryId: '',
    flavorId: '',
    purposeId: '',
    priceRangeId: '',
    isloading: true,
    nomore: false,
    moretext: "加载更多",
    singleStock: "",
    has_Filter: false,
    has_Filters: '../../images/sp_07.png',
    isShowShoppingchart: false,
    isShowChartChange: false,
    productMaskClass: "",
    Details: true,
    hasfilter: true,
    phoneSrc: '../../images/call.png',
    sHeight: 0,
    sideBar: false,
    bannerList: [],
    activeIndex: 0,
    brand: {}
  },
  onReady() {
    this.setData({
      sHeight: SystemUtil.getSystemInfo(false).windowHeight - 100
    })
  },
  onLoad: function (options) {
    // 开启转发按钮
    PagePromoterUtil.showShareMenu(true).then()
    // 页面初始化 options为页面跳转所带来的参数
    wx.removeStorageSync('checkedlis');
    // 是否开启侧边导航栏

    SessionUtil.getInstance().then(session => {
      // 注册当前页面的场景信息
      AppSceneUtil.setPageScene(this)
      // 初始化界面
      let specialString = wx.getStorageSync('specialString')
      let server = session.getTheSellingServerSync(),
        user = session.getTheSessionUserSync(),
        theAgent = SessionSellingServerUtil.getInstanceSync().getTheAgentSync();
      let titleName = server.showName
      let renderData = {
        name: '',
        specialString: '',
        pageNo: 1,
        ItemList: {},
        userid: user.userId,
        sideBar: theAgent.isShowItemListMenu
      }
      if (specialString) {
        renderData.specialString = specialString
      }
      if (options.search) {
        renderData.name = decodeURIComponent(options.search)
      } else if (options.name) {
        renderData.name = decodeURIComponent(options.name)
      } else {
        let tagValue = wx.getStorageSync('tagValue')
        if (tagValue) renderData.name = tagValue
      }
      this.setData(renderData)
      // 设置标题
      if (!titleName) {
        titleName = server.getTheAgentSync().showName + '酒库'
        if (specialString) titleName += `-${specialString}`
      }
      wx.setNavigationBarTitle({
        title: titleName
      })
      // 初始化商品列表
      if (theAgent.isShowItemListMenu) {
        this.querySideBar()
      } else {
        this.getItemList()
      }
    })
  },
  querySideBar() {
    JxbHttpClient.getClient().post({
      url: '/AppMaster/ItemFilter/getItemListMenu',
      data: {}
    }).then(jxbResp => {
      const itemList = jxbResp.data.list
      const {
        activeIndex
      } = this.data
      this.setData({
        bannerList: itemList,
        brand: itemList[activeIndex]
      })
      this.getItemList()
    })
  },
  onShow: function () {
    getApp().getSaleMode()
    wx.removeStorageSync('checkedlis');
    SessionUtil.getInstance().then(session => {
      // 注册当前页面的场景信息
      AppSceneUtil.setPageScene(this, false)
      // 初始化界面
      let specialString = wx.getStorageSync('specialString'),
        tagValue = wx.getStorageSync('tagValue')
      let server = session.getTheSellingServerSync(),
        user = session.getTheSessionUserSync()
      let titleName = server.showName
      // 设置标题
      if (!titleName) {
        titleName = server.getTheAgentSync().showName + '酒库'
        if (specialString) titleName += `-${specialString}`
      }
      wx.setNavigationBarTitle({
        title: titleName
      })
      // 页面渲染
      let renderData = {}
      let if_refresh = wx.getStorageSync("if_refresh"),
        doRenewList = false,
        hasfilter = this.data.hasfilter; //判断筛选条件是否存在true->不存在，false->存在  if_refresh = 1 ->不操作,= 2 ->带条件筛选, = 3 ->重置
      if (if_refresh == 2) {
        renderData = {
          userid: user.userId,
          specialString: specialString,
          name: tagValue,
          pageNo: 1,
        }
        console.log('from search', renderData)
        doRenewList = true
      } else if (if_refresh == 3 || if_refresh == 5) {
        wx.removeStorageSync("Filter");
        renderData = {
          name: "",
          userid: user.userId,
          pageNo: 1,
          Type: "",
          categoryId: "",
          flavorId: "",
          purposeId: "",
          priceRangeId: "",
          specialString: "",
          by_volumes: '../../images/sp_05.png',
          by_prices: '../../images/sp_05.png',
          has_Filters: '../../images/sp_07.png',
        }
        doRenewList = true
      } else if (if_refresh == 4) {
        renderData = {
          userid: user.userId,
          specialString: specialString,
          name: tagValue
        }
        if (hasfilter) {
          wx.setStorageSync("if_refresh", 3);
        } else {
          wx.setStorageSync("if_refresh", 2);
          renderData.hasfilter = true //重置过之后不刷
        }
      } else {
        renderData = {
          userid: user.userId,
          specialString: specialString,
          name: tagValue
        }
      }
      if (Object.keys(renderData).length > 0) {
        this.setData(renderData)
      }
      return doRenewList
    }).then(doRenewList => {
      if (doRenewList) {
        this.getItemList()
      }
      //加载购物车
      this.getCartProdsList();
      //当前顾问
      Common.showContips(this);

    })
  },
  onHide: function () {
    //当前顾问
    Common.show_bar(false, this);
    wx.setStorage({
      key: 'if_refresh',
      data: 3,
      success: function (res) {},
      fail: function (res) {},
      complete: function (res) {},
    })
    this.setData({
      isShowChartChange: false,
      name: ''
    })
  },



  /**
   * 下拉刷新
   */
  onPullDownRefresh: function () {
    var page = this;

    console.log('onPullDownRefresh 下拉刷新');

    setTimeout(function () {
      wx.stopPullDownRefresh();
    }, 1500);

    page.setData({
      pageNo: 1
    });
    page.getItemList('Refresh');

  },


  /**
   * 滑动触底
   */
  onReachBottom: function () {
    var page = this;
    console.log('onReachBottom 滑动触底');
    const {
      ItemList
    } = this.data
    if (ItemList.length === 0) return
    var page = this;
    var pageNo = page.data.pageNo;
    page.setData({
      pageNo: pageNo
    });
    page.getItemList('Page');
  },
  //当前顾问详细信息
  show_bar: function (flag = true) {
    Common.show_bar(true, this);
  },

  updateSearchKey: function (e) {
    this.setData({
      name: e.detail.value
    })
  },
  /**关闭加入购物车弹窗 */
  hideCartpop: function (e) {
    this.setData({
      isShowChartChange: false
    })
  },

  //客服按钮阻止冒泡
  preventBubble() {
    return false;
  },

  // 更新搜索关键词
  goSearch: function (e) {
    var page = this;
    var KEY = page.data.name;

    // 重置分页和计数
    this.setData({
      pageNo: 1,
    })

    // 重置搜索内容
    wx.setStorageSync('tagValue', this.data.name);
    wx.setStorageSync("if_refresh", 2);
    page.setData({
      hasfilter: false
    })
    page.setData({
      ItemList: "",
      // 筛选、排序条件清空
      by_volume: '',
      by_volumes: '../../images/sp_05.png',
      by_price: '',
      by_prices: '../../images/sp_05.png',
      has_Filter: false,
      has_Filters: '../../images/sp_07.png',
      Type: 0,
      categoryId: "",
      flavorId: "",
      purposeId: "",
      priceRangeId: ""
    })
    wx.setStorageSync('Filter', "");
    this.getItemList();
  },
  getItemList: function (action = '') {
    // 产品列表
    wx.showLoading({
      title: '数据加载中',
    })
    var page = this;
    var nowData = page.data.ItemList;
    var pageNo = page.data.pageNo;
    var name = page.data.name;
    var Type = page.data.Type;
    var categoryId = page.data.categoryId;
    var flavorId = page.data.flavorId;
    var purposeId = page.data.purposeId;
    var priceRangeId = page.data.priceRangeId;
    var specialString = page.data.specialString;
    page.setData({
      isloading: false,
      moretext: "加载更多",
      nomore: true
    });
    //加载购物车
    // page.getCartProdsList();
    if (pageNo < 1) {
      page.setData({
        isloading: true,
        nomore: false,
        moretext: "没有更多了"
      });
      wx.hideLoading();
      return;
    }
    const {
      brand
    } = this.data
    JxbHttpClient.getClient().get({
      url: '/AppMaster/Item/ItemList',
      data: {
        pageSize: pageSize,
        pageNo: pageNo,
        name: name,
        type: Type,
        categoryId: categoryId,
        flavorId: flavorId,
        purposeId: purposeId,
        priceRangeId: priceRangeId,
        specialString: specialString,
        menuValue: brand.value
      }
    }).then(jxbResp=>{
      pageNo++;
      var newData = itemList = jxbResp.data.list;
      if (itemList.length && itemList.length > 0) {
        if (itemList.length < 10) {
          page.setData({
            moretext: "没有更多了"
          });
        }
      } else {
        pageNo = -100;
        page.setData({
          isloading: true,
          nomore: false,
          moretext: "没有更多了",
        });
      }
      if (action == 'Refresh') {
        var itemList = jxbResp.data.list;
        if (itemList.length < 10) {
          page.setData({
            moretext: "没有更多了"
          });
        }
        // page.getCartProdsList();
        wx.stopPullDownRefresh();
      } else if (action == 'Page') {
        if (nowData.length) {
          var newData = nowData.concat(itemList)
        } else {
          var newData = itemList
        }
      }
      page.setData({
        ItemList: newData,
        pageNo: pageNo,
        isloading: true,
        nomore: false,
      });
      // 关闭加载
      wx.hideLoading();
    }).catch(err=>{
      InteractionUtil.showNotice(err.message)
    })
  },
  upper() {
    var page = this;
    page.setData({
      ItemList: {},
      pageNo: 1
    });
    page.getItemList('Refresh');
  },
  lower() {
    const {
      ItemList
    } = this.data
    if (ItemList.length === 0) return
    var page = this;
    var pageNo = page.data.pageNo;
    page.setData({
      pageNo: pageNo
    });
    page.getItemList('Page');
  },
  OrderBy: function (e) {
    var page = this;
    var ID = e.currentTarget.id;
    var by_volume = page.data.by_volume;
    var by_price = page.data.by_price;
    wx.setStorageSync("if_refresh", 2);
    page.setData({
      hasfilter: false
    })
    /*
        序规则:
        1 = 销量顺序
        2 = 销量倒序
        3 = 单价顺序
        4 = 单价倒序
        0 = 默认
    */

    if (ID == 'volume') {
      if (by_volume == '') {
        page.setData({
          by_volume: 'down',
          by_volumes: '../../images/sp_02.png',
          by_price: '',
          by_prices: '../../images/sp_05.png',
          Type: 2
        });
      } else if (by_volume == 'down') {
        page.setData({
          by_volume: 'up',
          by_volumes: '../../images/sp_03.png',
          by_price: '',
          by_prices: '../../images/sp_05.png',
          Type: 1
        });
      } else if (by_volume == 'up') {
        page.setData({
          by_volume: '',
          by_volumes: '../../images/sp_05.png',
          by_price: '',
          by_prices: '../../images/sp_05.png',
          Type: 0
        });
      }
    } else if (ID == 'price') {
      if (by_price == '') {
        page.setData({
          by_volume: '',
          by_volumes: '../../images/sp_05.png',
          by_price: 'down',
          by_prices: '../../images/sp_02.png',
          Type: 4
        });
      } else if (by_price == 'down') {
        page.setData({
          by_volume: '',
          by_volumes: '../../images/sp_05.png',
          by_price: 'up',
          by_prices: '../../images/sp_03.png',
          Type: 3
        });
      } else if (by_price == 'up') {
        page.setData({
          by_volume: '',
          by_volumes: '../../images/sp_05.png',
          by_price: '',
          by_prices: '../../images/sp_05.png',
          Type: 0
        });
      }
    }
    page.setData({
      pageNo: 1,
      orderBy: ID
    });
    page.getItemList();

  },
  goDetail: function (e) {
    var itemId = e.currentTarget.id;
    this.setData({
      Details: false,
    })
    wx.navigateTo({
      url: '/pages/product/detail/detail?itemId=' + itemId
    })
  },
  cancelCart: function () {
    var isShowChartChange = this.data.isShowChartChange;
    var bIsisShowChartChange = isShowChartChange ? false : true;
    this.setData({
      isShowChartChange: bIsisShowChartChange,
      productMaskClass: bIsisShowChartChange ? "product-mask" : "",
    });
  },
  goFilter: function () {
    wx.navigateTo({
      url: '/pages/product/filter/filter'
    })
  },
  AddCart: function (e) {
    var page = this;
    page.getCartProdsList();
    var ID = e.currentTarget.id
    var itemId = ID.split('-')[0];
    var stock = ID.split('-')[1];
    var chosenItem;
    var insideNum = 0;
    var thislist;
    var acartid;
    if (stock < 1) {
      page.setData({
        singleStock: stock
      })
      InteractionUtil.showNotice('库存不足！');
      return false;
    }

    page.setData({
      list_year: 0
    })
    // 显示年份
    JxbHttpClient.getClient().get({
      url: '/AppMaster/Item/getItemYearsList',
      data: {
        item_id: itemId
      }
    }).then(jxbResp=>{
      var normalInfo = jxbResp.data.item_info;
      var list_year = jxbResp.data.item_year_list;
      var activity = normalInfo.activity_category;
      if (activity != 0) {
        activity = activity.split(",");
      }
      page.setData({
        chosenItem: normalInfo,
        list_year: list_year,
        activity: activity
      })
    })
    page.setData({
      isShowChartChange: true,
      chosenNum: 1,
      singleStock: stock,
      sitemId: itemId,
      oldNum: insideNum
    });
  },
  // 点击年份切换商品
  changeYear: function (e) {
    var page = this;
    var itemId = e.currentTarget.id;
    var list_year = page.data.list_year;
    var chosenItem = page.data.chosenItem;
    if (chosenItem.item_id == itemId) {
      return false;
    } else {
      for (var i = 0; i < list_year.length; i++) {
        if (itemId == list_year[i].item_id) {
          var activity = list_year[i].activity_category;
          if (activity != 0) {
            activity = activity.split(",");
          }
          page.setData({
            chosenItem: list_year[i],
            sitemId: itemId,
            activity: activity
          })
        }
      }
    }
  },

  goCart: function () {
    let num = this.data.chosenNum; //输入框的数量
    num = parseInt(num);
    JxbHttpClient.getClient().post({
      url: '/AppMaster/PosCart/PosAddCart',
      data: {
        number: num,
        itemId: this.data.sitemId
      }
    }).then(jxbResp=>{
      InteractionUtil.showSuccess('添加成功');
      this.getCartProdsList();
      this.cancelCart();
      this.setData({
        chosenNum: 1
      })
    }).catch(err=>{
      InteractionUtil.showNotice(err.message)
    })
  },
  reduceSingle: function () {
    let num = this.data.chosenNum - 1;
    if (num <= 1) {
      this.setData({
        chosenNum: 1,
      })
    } else {
      this.setData({
        chosenNum: num,
      })
    }
  },
  addToCartSingle: function () {
    var page = this;
    var stock = page.data.singleStock;
    var num = page.data.chosenNum + 1;
    if (num >= stock) {
      InteractionUtil.showNotice('库存不足！');
    } else {
      page.setData({
        chosenNum: num,
      })
    }
  },
  toZero: function (e) {
    var num = e.detail.value;
    if (num.length == 0) {
      this.setData({
        chosenNum: 1
      })
    }
  },
  updateNum: function (e) {
    var num = e.detail.value;
    var tnum = parseInt(num);
    if (num.length == 0) {
      this.setData({
        chosenNum: 1
      })
    } else {
      this.setData({
        chosenNum: tnum
      })
    }
  },
  getCartProdsList: function (autoRefreshToken = true) {
    let reqParams = {
      url:'AppMaster/PosCart/cartDetail'
    }
    if(autoRefreshToken === false){
      reqParams.interceptBizEvent = ~JxbHttpInterceptor.EVENT_TOKEN_EXPIRED & JxbHttpInterceptor.EVENT_ALL
    }
    JxbHttpClient.getClient().get(reqParams).then(jxbResp => {
      let respData = jxbResp.data,
        products = respData.productsList,
        list = respData.activity_list
      let total = 0,
        gross = 0.00,
        itemids = [],
        limits = [];
      for (let z = 0; z < list.length; z++) {
        if (list[z].activity_category == 6) {
          itemids = itemids.concat(list[z].itemids);
        }
        if (list[z].activity_category == 4) {
          limits = limits.concat(list[z].itemids);
        }
      }
      for (let i = 0; i < products.length; i++) {
        total = total + products[i].carNumber;
        gross = gross + products[i].carNumber * products[i].show_price;
        let z = Common.contains(itemids, products[i].itemid),
          w = Common.contains(limits, products[i].itemid);
        if (z && w) {
          products[i].activity_list = ['秒杀', '限购']
        } else {
          if (z) {
            products[i].activity_list = ['秒杀'];
          }
          if (w) {
            products[i].activity_list = ['限购'];
          }
        }
      }
      respData.total = total;
      respData.gross = gross.toFixed(2);
      respData.productsList = products;
      this.setData({
        productsList: respData,
      })
    }).catch(err => {
      if(err instanceof SessionExpiredError){
        console.log('会话过期，直接显示0', err)
        // 如果会话过期，直接显示0
        this.setData({
          total: 0,
          gross: 0,
          productMaskClass: "",
          productsList: {},
        })
        return;
      }
      console.log(err)
      InteractionUtil.showNotice(err.message);
      this.setData({
        productMaskClass: "",
        productsList: {},
      })
    })
  },
  goCarts: function () {
    wx.switchTab({
      url: '/pages/shoppingcart/index'
    })
  },
  clearStorageSync: function () {
    wx.setStorageSync("dilivery", '');
    wx.setStorageSync("invoice", {});
    wx.setStorageSync("pay", {});
  },
  onShareAppMessage: function () {
    let agentName = '',
      search = this.data.name,
      server = SessionUtil.getInstanceSync().getTheSellingServerSync()
    if (server) {
      let agent = server.getTheAgentSync();
      agentName = agent.showName + '酒库'
    }
    // 构造并返回自定义数据
    return (new PagePromoter(this.route, {
        search: search
      }))
      .setShareTitle(agentName)
      .buildShareInfo()
  },
  goSearchView() {
    wx.navigateTo({
      url: '../../search/index',
    })
  },
  call(e) {
    const {
      phone
    } = e.currentTarget.dataset
    getApp().call(phone)
  },
  queryProduct(e) {
    const {
      dataset
    } = e.currentTarget
    const {
      index
    } = dataset
    const {
      bannerList
    } = this.data
    const brand = bannerList[index]
    this.setData({
      activeIndex: index,
      brand,
      ItemList: [],
      pageNo: 1,
      name: '',
      Type: '',
      categoryId: '',
      flavorId: '',
      purposeId: '',
      priceRangeId: '',
    })
    this.getItemList()
  }
})